// TextureList.cpp: implementation of the CTextureList class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "client.h"
#include "TextureList.h"

#include "xTexture.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CTextureList::CTextureList()
{
	pFirst = pLast = NULL;
	Clear();
}

CTextureList::~CTextureList()
{
	Clear();
}


void CTextureList::Clear()
{
	TotNum = 0;
	pLast = NULL;
	if(pFirst == NULL) return;

	TEXTURELIST* pNext = pFirst;
	while(pNext)
	{
		TEXTURELIST* pNow = pNext;
		pNext = pNow->pNextNode;
		delete pNow;
	}

	pFirst = NULL;
	return;
}

BOOL CTextureList::AddTexture(xTexture* ptex)
{
	if(!ptex) return FALSE;

	TEXTURELIST* pNew = new TEXTURELIST();
	if(pNew==NULL) return FALSE;

	pNew->pTex = ptex;

	TotNum++;

	if(pFirst == NULL) {
		pFirst = pLast = pNew;
		return TRUE;
	}

	pLast->pNextNode = pNew;
	pNew->pPreNode = pLast;
	pLast = pNew;

	return TRUE;
}


BOOL CTextureList::DelTexture(xTexture* ptex)
{
	if(!ptex) return FALSE;
	if(TotNum <= 0) return FALSE;

	TEXTURELIST* pNode = FindTexture(ptex);
	if(!pNode) return FALSE;

	if(TotNum>0) TotNum--;

	TEXTURELIST* pPre = pNode->pPreNode;
	TEXTURELIST* pNext = pNode->pNextNode;
	
	if(pPre) pPre->pNextNode = pNext;
	else pFirst = pNext;

	if(pNext) pNext->pPreNode = pPre;
	else pLast = pPre;

	if(!pPre && !pNext) pFirst = NULL;

	delete pNode;

	return TRUE;
}

TEXTURELIST* CTextureList::FindTexture(xTexture* ptex)
{
	TEXTURELIST* pNext = pFirst;
	while(pNext) {
		if(pNext->pTex == ptex) return pNext;
		pNext = pNext->pNextNode;
	}
	return NULL;
}

void CTextureList::DestroyAllTexture()
{
	TEXTURELIST* pNext = pFirst;
	xTexture* ptex = NULL;
	while(pNext) {
		ptex = pNext->pTex;
		pNext = pNext->pNextNode;
		if(!ptex) continue;
		ptex->Destroy();
		ptex->m_bDestroyMarked = TRUE;
	}
}
